//
//  NoticeViewController.m
//  SportsSocial
//
//  Created by yull on 14/10/29.
//  Copyright (c) 2014年 yull. All rights reserved.
//

#import "NoticeViewController.h"
#import "CommonNewsCell.h"
#import "NewsNet.h"
#import "NewsModel.h"
#import "GroupNet.h"
#import "NearGroupCell.h"

@interface NoticeViewController () <UITableViewDataSource,UITableViewDelegate>

@property (nonatomic, strong) UITableView *tableViewNotice;

@property (nonatomic, strong) NSMutableArray *arrayNoticeNews;
@property (nonatomic, strong) NSMutableArray *arrayGroup;

@property (nonatomic, assign) BOOL show1;
@property (nonatomic, assign) BOOL show2;

@property (nonatomic, strong) UIView *sectionView1;
@property (nonatomic, strong) UIView *sectionView2;

@property (nonatomic, strong) UIImageView *arrowImageView1;
@property (nonatomic, strong) UIImageView *arrowImageView2;

@end

@implementation NoticeViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self initNavibar];
    
    [self createTableView];
    
    [self createSectionView];
    
    [self getNoticeNews];
    
    [self getNoticeGroupList];
}

- (void)initNavibar
{
    self.navigationItem.title = @"我的关注";
    
    [self addCommonBackButton];
}

- (void)createTableView
{
    CGRect rect = CGRectMake(0, 0, self.view.width, self.view.height-Navibar_Height);
    self.tableViewNotice = [[UITableView alloc] initWithFrame:rect];
    self.tableViewNotice.backgroundColor = [UIColor clearColor];
    self.tableViewNotice.delegate = self;
    self.tableViewNotice.dataSource = self;
    self.tableViewNotice.separatorInset = UIEdgeInsetsZero;
    [self.view addSubview:self.tableViewNotice];
    
    self.tableViewNotice.tableFooterView = [[UIView alloc] init];
}

- (void)createSectionView
{
    self.sectionView1 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 50)];
    
    CGRect rect = CGRectMake(10, 15, 20, 20);
    UIImageView *groupIcon = [[UIImageView alloc] initWithFrame:rect];
    groupIcon.image = [UIImage imageNamed:@"notice_icon_group"];
    [self.sectionView1 addSubview:groupIcon];
    
    rect = CGRectMake(groupIcon.right + 10, 0, self.sectionView1.width - groupIcon.right - 10, self.sectionView1.height);
    UILabel *label1 = [[UILabel alloc] initWithFrame:rect];
    label1.backgroundColor = [UIColor clearColor];
    label1.text = @"俱乐部";
    label1.font = [UIFont systemFontOfSize:18.0f];
    label1.textColor = [UIColor blackColor];
    [self.sectionView1 addSubview:label1];
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.sectionView1.height - 0.5f, self.sectionView1.width, 0.5)];
    lineView.backgroundColor = RGB(234, 234, 234);
    [self.sectionView1 addSubview:lineView];
    
    self.sectionView2 = [[UIView alloc] initWithFrame:CGRectMake(0, 0, self.view.width, 50)];
    
    rect = CGRectMake(10, 15, 20, 20);
    UIImageView *newsIcon = [[UIImageView alloc] initWithFrame:rect];
    newsIcon.image = [UIImage imageNamed:@"notice_icon_news"];
    [self.sectionView2 addSubview:newsIcon];
    
    rect = CGRectMake(newsIcon.right + 10, 0, self.sectionView2.width - newsIcon.right - 10, self.sectionView2.height);
    UILabel *label2 = [[UILabel alloc] initWithFrame:rect];
    label2.backgroundColor = [UIColor clearColor];
    label2.text = @"新闻 小知识";
    label2.font = [UIFont systemFontOfSize:18.0f];
    label2.textColor = [UIColor blackColor];
    [self.sectionView2 addSubview:label2];
    
    lineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.sectionView2.height - 0.5f, self.sectionView2.width, 0.5)];
    lineView.backgroundColor = RGB(234, 234, 234);
    [self.sectionView2 addSubview:lineView];
    
    UIButton *button1 = [UIButton buttonWithType:UIButtonTypeCustom];
    button1.frame = self.sectionView1.bounds;
    button1.backgroundColor = [UIColor clearColor];
    [button1 addTarget:self action:@selector(onClickSection1:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionView1 addSubview:button1];
    
    UIButton *button2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button2.frame = self.sectionView1.bounds;
    button2.backgroundColor = [UIColor clearColor];
    [button2 addTarget:self action:@selector(onClickSection2:) forControlEvents:UIControlEventTouchUpInside];
    [self.sectionView2 addSubview:button2];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 && self.show1) {
        return self.arrayGroup.count;
    }else if (section == 1 && self.show2) {
        return self.arrayNoticeNews.count;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0 && self.show1) {
        return [NearGroupCell nearGroupCellHeight];
    }else if (indexPath.section == 1 && self.show2){
        return [CommonNewsCell defaultCommonNewsCellHeight];
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        static NSString *groupIdentifier = @"GroupCell";
        NearGroupCell *groupCell = [tableView dequeueReusableCellWithIdentifier:groupIdentifier];
        if (!groupCell) {
            groupCell = [[NearGroupCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:groupIdentifier];
            groupCell.distanceLabel.hidden = YES;
        }
        [groupCell drawCellWithNearGroup:[self.arrayGroup objectAtIndex:indexPath.row]];
        return groupCell;
    }else {
        static NSString *noticeNewsIdentifier = @"NoticeNewsCell";
        CommonNewsCell *newsCell = [tableView dequeueReusableCellWithIdentifier:noticeNewsIdentifier];
        if (!newsCell) {
            newsCell = [[CommonNewsCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:noticeNewsIdentifier];
        }
        
        [newsCell drawCellWithNewsModel:[self.arrayNoticeNews objectAtIndex:indexPath.row]];
        return newsCell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        NearGroup *nearGroup = [self.arrayGroup objectAtIndex:indexPath.row];
        
        UIViewController *groupInfoViewController = [Interface createGroupInfoWithNearGroup:nearGroup];
        [self.navigationController pushViewController:groupInfoViewController animated:YES];
        
    }else if (indexPath.section == 1){
        
        NewsModel *newsModel = [self.arrayNoticeNews objectAtIndex:indexPath.row];
        
        UIViewController *newsContentViewController = [Interface createNewsContentWithNews:newsModel];
        [self.navigationController pushViewController:newsContentViewController animated:YES];
    }
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除";
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        NearGroup *group = [self.arrayGroup objectAtIndex:indexPath.row];
        [self unFollowWithGroup:group];
    }else if (indexPath.section == 1) {
        NewsModel *news =  [self.arrayNoticeNews objectAtIndex:indexPath.row];
        [self removeNoticeNewsWithNews:news];
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return self.sectionView1.height;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return self.sectionView1;
    }else {
        return self.sectionView2;
    }
}

#pragma mark - net
//新闻收藏列表
- (void)getNoticeNews
{
    if (!self.arrayNoticeNews) {
        self.arrayNoticeNews = [NSMutableArray array];
    }
    
    @weakify(self);
    [NewsNet getNoticeNewsWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            [self.arrayNoticeNews addObjectsFromArray:[NewsModel newsArrayWithDictArray:[responseObject objectForKey:@"data"]]];
            
            [self getNoticeKnowLedge];
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });

    }];
}

//小知识收藏列表
- (void)getNoticeKnowLedge
{
    @weakify(self);
    [NewsNet getNoticeKnowLedgeWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            [self.arrayNoticeNews addObjectsFromArray:[NewsModel newsArrayWithDictArray:[responseObject objectForKey:@"data"]]];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableViewNotice reloadData];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });

    }];
}

//新闻删除收藏
- (void)removeNoticeNewsWithNews:(NewsModel *)newsModel
{
    @weakify(self);
    [NewsNet removeNewsFromFavoriteWithNewsId:newsModel.newsId successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSInteger index = [self.arrayNoticeNews indexOfObject:newsModel];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:1];
            [self.arrayNoticeNews removeObject:newsModel];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"取消收藏成功!" time:2];
                [self.tableViewNotice deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            });
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });

    }];
}

//俱乐部收藏列表
- (void)getNoticeGroupList
{
    if (!self.arrayGroup) {
        self.arrayGroup = [NSMutableArray array];
    }else {
        [self.arrayGroup removeAllObjects];
    }
    
    @weakify(self);
    [GroupNet getNoticeGroupWithSuccessBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSDictionary *dictArray = [responseObject objectForKey:@"data"];
            for (NSDictionary *dict in dictArray) {
                [self.arrayGroup addObject:[NearGroup nearGroupWithDict:dict]];
            }
            
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
        
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });

    }];
}

//取消收藏俱乐部
- (void)unFollowWithGroup:(NearGroup *)group
{
    @weakify(self);
    [GroupNet deleteNoticeGroupWithGroupId:group.group_id successBlock:^(AFHTTPRequestOperation *operation, id responseObject) {
        @strongify(self);
        BOOL success = [[responseObject objectForKey:@"success"] boolValue];
        if (success) {
            NSInteger index = [self.arrayGroup indexOfObject:group];
            NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
            [self.arrayGroup removeObject:group];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:@"取消收藏成功!" time:2];
                [self.tableViewNotice deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            });
        } else {
            NSString *message = [responseObject objectForKey:@"message"];
            
            dispatch_async(dispatch_get_main_queue(), ^{
                [self showText:message time:2];
            });
        }
    } failBlock:^(AFHTTPRequestOperation *operation, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self showText:@"网络连接失败" time:2];
        });

    }];
}

#pragma mark - 
- (void)onClickSection1:(id)sender
{
    self.show1 = !self.show1;
    
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:0];
    [self.tableViewNotice reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)onClickSection2:(id)sender
{
    self.show2 = !self.show2;
    
    NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
    [self.tableViewNotice reloadSections:indexSet withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)dealloc
{
    self.tableViewNotice.delegate = nil;
    self.tableViewNotice.dataSource = nil;
}
@end
